<?php

namespace App\Http\Controllers\Api;

use App\Models\Position;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PositionController extends BaseController
{
    /**
     * 获取岗位列表
     */
    public function index(Request $request)
    {
        try {
            $query = Position::with(['superior', 'subordinates']);

            // 搜索条件
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
                });
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 类别筛选
            if ($request->has('category')) {
                $query->byCategory($request->category);
            }

            // 层级筛选
            if ($request->has('level')) {
                $query->byLevel($request->level);
            }

            // 薪资范围筛选
            if ($request->has('min_salary') || $request->has('max_salary')) {
                $minSalary = $request->get('min_salary', 0);
                $maxSalary = $request->get('max_salary', PHP_INT_MAX);
                $query->bySalaryRange($minSalary, $maxSalary);
            }

            // 空缺岗位筛选
            if ($request->boolean('with_vacancy')) {
                $query->withVacancy();
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $positions = $query->paginate($perPage);

            return $this->paginate($positions, '获取岗位列表成功');
        } catch (\Exception $e) {
            return $this->error('获取岗位列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取岗位详情
     */
    public function show(Position $position)
    {
        try {
            $position->load([
                'superior',
                'subordinates',
                'employees' => function ($query) {
                    $query->active()->with(['user', 'departmentInfo']);
                },
                'departmentPositions',
                'probationSettings',
            ]);

            return $this->success($position, '获取岗位详情成功');
        } catch (\Exception $e) {
            return $this->error('获取岗位详情失败：' . $e->getMessage());
        }
    }

    /**
     * 创建岗位
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:50|unique:positions',
                'name' => 'required|string|max:100',
                'department_id' => 'nullable|exists:departments,id',
                'level' => 'required|integer|min:1',
                'category' => 'required|in:management,technical,operational,support,other',
                'description' => 'nullable|string|max:500',
                'responsibilities' => 'nullable|array',
                'requirements' => 'nullable|array',
                'min_salary' => 'nullable|numeric|min:0',
                'max_salary' => 'nullable|numeric|min:0|gte:min_salary',
                'report_to' => 'nullable|exists:positions,id',
                'is_management' => 'sometimes|boolean',
                'vacancy_count' => 'nullable|integer|min:0',
                'sort_order' => 'nullable|integer|min:0',
                'notes' => 'nullable|string',
            ]);

            // 创建岗位
            $position = Position::create([
                'code' => $data['code'],
                'name' => $data['name'],
                'department_id' => $data['department_id'] ?? null,
                'level' => $data['level'],
                'category' => $data['category'],
                'description' => $data['description'] ?? null,
                'responsibilities' => $data['responsibilities'] ?? [],
                'requirements' => $data['requirements'] ?? [],
                'min_salary' => $data['min_salary'] ?? null,
                'max_salary' => $data['max_salary'] ?? null,
                'report_to' => $data['report_to'] ?? null,
                'is_management' => $data['is_management'] ?? false,
                'vacancy_count' => $data['vacancy_count'] ?? 0,
                'sort_order' => $data['sort_order'] ?? 0,
                'status' => 'active',
                'notes' => $data['notes'] ?? null,
            ]);

            // 记录操作日志
            $this->logOperation('create', 'position', [
                'position_id' => $position->id,
                'code' => $position->code,
                'name' => $position->name,
            ]);

            $position->load(['superior']);

            return $this->success($position, '创建岗位成功', 201);
        } catch (\Exception $e) {
            return $this->error('创建岗位失败：' . $e->getMessage());
        }
    }

    /**
     * 更新岗位信息
     */
    public function update(Request $request, Position $position)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => ['sometimes', 'required', 'string', 'max:50', Rule::unique('positions')->ignore($position->id)],
                'name' => 'sometimes|required|string|max:100',
                'department_id' => 'sometimes|nullable|exists:departments,id',
                'level' => 'sometimes|required|integer|min:1',
                'category' => 'sometimes|required|in:management,technical,operational,support,other',
                'description' => 'sometimes|nullable|string|max:500',
                'responsibilities' => 'sometimes|nullable|array',
                'requirements' => 'sometimes|nullable|array',
                'min_salary' => 'sometimes|nullable|numeric|min:0',
                'max_salary' => 'sometimes|nullable|numeric|min:0|gte:min_salary',
                'report_to' => 'sometimes|nullable|exists:positions,id',
                'is_management' => 'sometimes|boolean',
                'vacancy_count' => 'sometimes|nullable|integer|min:0',
                'sort_order' => 'sometimes|nullable|integer|min:0',
                'status' => 'sometimes|required|in:active,inactive,obsolete',
                'notes' => 'sometimes|nullable|string',
            ]);

            $position->update($data);

            // 记录操作日志
            $this->logOperation('update', 'position', [
                'position_id' => $position->id,
                'changes' => $data,
            ]);

            $position->load(['superior']);

            return $this->success($position, '更新岗位信息成功');
        } catch (\Exception $e) {
            return $this->error('更新岗位信息失败：' . $e->getMessage());
        }
    }

    /**
     * 删除岗位
     */
    public function destroy(Position $position)
    {
        try {
            // 检查是否有员工在此岗位
            if ($position->employees()->count() > 0) {
                return $this->error('该岗位还有员工，无法删除');
            }

            // 检查是否有子岗位
            if ($position->subordinates()->count() > 0) {
                return $this->error('该岗位有子岗位，无法删除');
            }

            $position->delete();

            // 记录操作日志
            $this->logOperation('delete', 'position', [
                'position_id' => $position->id,
                'code' => $position->code,
                'name' => $position->name,
            ]);

            return $this->success(null, '删除岗位成功');
        } catch (\Exception $e) {
            return $this->error('删除岗位失败：' . $e->getMessage());
        }
    }

    /**
     * 获取岗位统计信息
     */
    public function statistics(Request $request)
    {
        try {
            $stats = [
                'total_positions' => Position::count(),
                'active_positions' => Position::active()->count(),
                'management_positions' => Position::management()->count(),
                'with_vacancy' => Position::withVacancy()->count(),
                'by_category' => Position::selectRaw('category, COUNT(*) as count')
                    ->groupBy('category')
                    ->get(),
                'by_level' => Position::selectRaw('level, COUNT(*) as count')
                    ->groupBy('level')
                    ->orderBy('level')
                    ->get(),
                'salary_ranges' => [
                    'min_avg' => Position::avg('min_salary'),
                    'max_avg' => Position::avg('max_salary'),
                    'total_budget' => Position::sum('min_salary') + Position::sum('max_salary'),
                ],
            ];

            return $this->success($stats, '获取岗位统计信息成功');
        } catch (\Exception $e) {
            return $this->error('获取岗位统计信息失败：' . $e->getMessage());
        }
    }

    /**
     * 获取岗位下的员工
     */
    public function employees(Position $position, Request $request)
    {
        try {
            $employees = $position->employees()
                ->with(['user', 'departmentInfo'])
                ->active()
                ->paginate($request->get('per_page', 15));

            return $this->paginate($employees, '获取岗位员工列表成功');
        } catch (\Exception $e) {
            return $this->error('获取岗位员工列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取岗位层级结构
     */
    public function hierarchy(Request $request)
    {
        try {
            $positions = Position::active()
                ->with(['superior', 'subordinates'])
                ->orderBy('level')
                ->orderBy('sort_order')
                ->get()
                ->groupBy('level');

            return $this->success($positions, '获取岗位层级结构成功');
        } catch (\Exception $e) {
            return $this->error('获取岗位层级结构失败：' . $e->getMessage());
        }
    }

    /**
     * 更新岗位薪资范围
     */
    public function updateSalary(Request $request, Position $position)
    {
        try {
            $data = $this->validateRequest($request, [
                'min_salary' => 'required|numeric|min:0',
                'max_salary' => 'required|numeric|min:0|gte:min_salary',
            ]);

            $position->update($data);

            return $this->success($position, '更新岗位薪资范围成功');
        } catch (\Exception $e) {
            return $this->error('更新岗位薪资范围失败：' . $e->getMessage());
        }
    }
}
